<template>
  <div :data-level="level" class="Nav-container absolute left-0 top-0">
    <div class="title" @click="goBack()">
      <div>
        <!-- 前头图标 -->
        <svg
          v-if="level > 0"
          height="24"
          viewBox="0 0 24 24"
          width="24"
          xmlns="http://www.w3.org/2000/svg"
        >
          <path
            d="M22 13v-2H5.828l3.95-3.95l-1.414-1.414L2 12l6.364 6.364l1.414-1.414L5.828 13z"
            fill="currentColor"
          />
        </svg>
      </div>
      <div>
        {{ title }}
      </div>
    </div>
    <div class="list">
      <ul v-for="item in navData" :key="item.name">
        <li class="list-item" @click="handleClick(item)">
          {{ item.name }} {{ item.children.length > 0 ? '>' : '' }}
        </li>
      </ul>
    </div>
  </div>

  <component :is="newDome" v-if="newDome" :data-level="level + 1" />
</template>

<script setup lang="ts">
import { h, onMounted, type PropType, ref } from 'vue';

import { useDomeStore } from '#/store/dome';

const props = defineProps({
  /** 层级 */
  level: {
    type: Number,
    default: 0,
  },
  /** 标题 */
  title: {
    type: String,
    default: '',
  },

  /** 导航数据 */
  navData: {
    type: Array as PropType<any[]>,
    default: () => [],
  },
});

const newDome = ref<any>(null); // 新组件
// 仓库实例
const domeStore = useDomeStore();

// 更新位置函数
const Updateposition = () => {
  document.querySelectorAll('.Nav-container').forEach((item: any) => {
    const newLevel = item.dataset.level;
    item.style.transform = `translateX(${(newLevel - domeStore.currentLevel) * 100}%)`;
  });
};

// 回退函数
const goBack = () => {
  if (domeStore.currentLevel === 0) {
    return;
  }
  domeStore.currentLevel--;
  Updateposition();
};
// 处理项函数
const handleClick = (item: any) => {
  if (item.children.length === 0) {
    return;
  }
  domeStore.addCurrentLevel();
  // 点击后更新位置
  Updateposition();
  newDome.value = h(NavDome, {
    level: domeStore.currentLevel,
    dataLevel: domeStore.currentLevel + 1,
    navData: item.children,
    title: item.name,
  });
};

// 首次加载更新位置
onMounted(() => {
  // 第一层不自动更新位置
  if (props.level === 0) {
    return;
  }
  // 右侧隐藏的菜单向左移动显示满屏
  setTimeout(() => {
    Updateposition();
  }, 0);
});
defineExpose({
  Updateposition,
});
</script>

<!-- 必须添加命名实现递归 -->
<script lang="ts">
export default {
  name: 'NavDome',
};
</script>
<style scoped lang="scss">
// 容器样式
.Nav-container {
  width: 100%;
  height: 100%;
  padding: 16px;
  box-shadow: 0 0 10px rgb(0 0 0 / 10%);
  transition: all 0.3s ease;
  transform: translateX(100%);
}

// 标题样式
.title {
  display: flex;
  gap: 10px;
  align-items: center;
  height: 50px;
  font-size: 20px;
  font-weight: bold;
  line-height: 50px;
}

// 列表样式
.list {
  height: 150px;
}

// 列表项样式
.list-item {
  height: 50px;
  padding: 10px;
  font-size: 16px;
  line-height: 50px;
  border-bottom: 1px solid #f0f0f0;
}
</style>
